import time
import json
import os
from typing import List, Dict, Optional
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.edge.service import Service

# ==== 配置区，请根据实际修改 ====
WEBDRIVER_PATH: Optional[str] = r"H:\chromedriver64\msedgedriver.exe"  # 指向 msedgedriver.exe 的完整路径，若已在 PATH 可设为 None
COOKIES_FILE = "taobao_cookies.json"
TAOBAO_URL = "https://www.taobao.com/"
# =================================

def create_edge_driver(webdriver_path: Optional[str] = None, headless: bool = False):
    """
    尝试兼容 selenium 的不同版本来创建 Edge driver：
    - 优先用 Service + Options（selenium 4+）
    - 若失败，回退到 executable_path 方式（旧版 selenium）
    """
    options = Options()
    if headless:
        options.add_argument("--headless")
        options.add_argument("--window-size=1920,1080")

    try:
        # 尝试兼容 Selenium 4.x (使用 service 和 options)
        if webdriver_path:
            service = Service(executable_path=webdriver_path)
            driver = webdriver.Edge(service=service, options=options)
        else:
            driver = webdriver.Edge(options=options)
    except TypeError as e:
        print(f"出现错误，可能是 selenium 版本不兼容，尝试回退：{e}")
        # 回退到 Selenium 3.x 兼容方式
        driver = None

    if driver is None:
        # 如果仍然没有创建成功，回退到旧版 Selenium 3.x 方式
        print("正在使用旧版构造方式启动 Edge WebDriver...")
        if webdriver_path:
            driver = webdriver.Edge(executable_path=webdriver_path)
        else:
            driver = webdriver.Edge()

    # 基本设置
    driver.maximize_window()
    driver.implicitly_wait(10)
    return driver

def load_cookies_file(filepath: str) -> List[Dict]:
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"未找到 cookie 文件：{filepath}")
    with open(filepath, "r", encoding="utf-8") as f:
        cookies = json.load(f)
    if not isinstance(cookies, list):
        raise ValueError("cookie 文件格式异常，应为一个列表（list of dicts）")
    return cookies

def sanitize_cookie_for_selenium(cookie: Dict) -> Dict:
    """
    处理 cookie，删除或转换不兼容字段（如 domain/expiry 的类型问题）
    返回可被 driver.add_cookie() 接受的 cookie dict
    """
    c = {}
    for k in ("name", "value", "path", "domain", "secure", "httpOnly", "expiry", "sameSite"):
        if k in cookie:
            c[k] = cookie[k]
    if "expiry" in c:
        try:
            c["expiry"] = int(c["expiry"])
        except Exception:
            c.pop("expiry", None)
    return c

def add_cookies_to_driver(driver, cookies: List[Dict], force_domain_remove: bool = True):
    """
    注入 cookies。
    若 force_domain_remove=True，会在注入前删除 cookie 中的 domain 字段（避免跨域错误）。
    """
    for cookie in cookies:
        try:
            c = sanitize_cookie_for_selenium(cookie)
            if force_domain_remove and "domain" in c:
                c.pop("domain", None)
            driver.add_cookie(c)
        except Exception as e:
            print(f"注入 cookie {cookie.get('name')} 失败：{e}")

def check_login_status(driver, expected_nick: Optional[str] = None) -> bool:
    """
    检查是否登录成功
    """
    time.sleep(1)
    selectors = [
        (By.XPATH, "//a[contains(@class,'site-nav-login-info-nick')]"),
        (By.CSS_SELECTOR, ".site-nav-user .site-nav-login-info-nick"),
        (By.XPATH, "//div[contains(@class,'site-nav-user')]/a"),
    ]
    for by, sel in selectors:
        try:
            el = driver.find_element(by, sel)
            text = el.text.strip()
            if text:
                print("检测到昵称/用户信息：", text)
                if expected_nick:
                    return text == expected_nick
                return True
        except Exception:
            continue
    try:
        el = driver.find_element(By.LINK_TEXT, "亲，请登录")
        if el:
            print("检测到未登录提示（亲，请登录）")
            return False
    except Exception:
        pass
    return False

def main():
    # 创建 driver（自动兼容）
    driver = create_edge_driver(WEBDRIVER_PATH, headless=False)
    try:
        driver.get(TAOBAO_URL)
        time.sleep(1)

        try:
            saved_cookies = load_cookies_file(COOKIES_FILE)
        except FileNotFoundError:
            print(f"未找到文件 {COOKIES_FILE}。请先运行保存 cookie 的脚本或手动保存 cookie 后再试。")
            return
        except Exception as e:
            print("读取 cookie 文件失败：", e)
            return

        add_cookies_to_driver(driver, saved_cookies, force_domain_remove=True)

        driver.refresh()
        time.sleep(2)

        if check_login_status(driver):
            print("检测到已登录（可能）。自动登录成功！")
        else:
            print("未检测到登录状态。cookie 可能已失效或淘宝触发了风控验证。")

        print("脚本将在 10 秒后退出（请观察浏览器状态）...")
        time.sleep(10)

    finally:
        try:
            driver.quit()
        except Exception:
            pass

if __name__ == "__main__":
    main()
